package com.tjw.telecomver2.ex.handler;

import com.tjw.telecomver2.ex.CoolSharkServiceException;
import com.tjw.telecomver2.web.JsonResult;
import com.tjw.telecomver2.web.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler() {
        log.debug("创建了全局异常处理器");
    }

    @ExceptionHandler
    public JsonResult<Void> CoolSharkExceptionHandler(CoolSharkServiceException e) {
        log.debug("捕获到一个CoolSharkServiceException, 准备统一集中处理...");

        return JsonResult.failed(e);
    }

    @ExceptionHandler
    public JsonResult<Void> BindExceptionHandler(BindException e) {
        log.debug("捕获到一个BindException, 准备统一集中处理...");
//        StringJoiner stringJoiner = new StringJoiner(",", "请求参数格式错误, ", "!!!");
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError fieldError : fieldErrors) {
//            String defaultMessage = fieldError.getDefaultMessage();
//            stringJoiner.add(defaultMessage);
//        }
//        return JsonResult.failed(ResponseCode.ERR_BAD_REQUEST, stringJoiner.toString());
        String defaultMessage = e.getFieldError().getDefaultMessage();
        return JsonResult.failed(ResponseCode.ERR_BAD_REQUEST, defaultMessage);
    }

    @ExceptionHandler
    public JsonResult<Void> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        log.debug("捕获到一个ConstraintViolationException, 准备统一集中处理...");
        StringJoiner stringJoiner = new StringJoiner(", ");
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            stringJoiner.add(constraintViolation.getMessage());
        }
        return JsonResult.failed(ResponseCode.ERR_BAD_REQUEST, stringJoiner.toString());
    }
}
